<template>
    <div id="container">
        <div id="editor-box">
            <canvas id="THREE-canvas"></canvas>
        </div>
        <div class="panel">
            <button @click="handleAddGreenHouse">添加【大棚】</button>
            <button @click="handleAddField">添加【田块】</button>
            <button @click="spaceAssembler.closeEdit">关闭编辑</button>
            <button @click="spaceAssembler.getSaveData">获取保存信息</button>
            <div class="greenhouse-list">
                <h1>大棚列表</h1>
                <div v-for="(item) in greenhouses" :key="item.id" class="greenhouse-item">🏛大棚{{ item.id }}
                    <button @click="spaceAssembler.openEdit(item)">编辑</button>
                    <button @click="spaceAssembler.removeGreenHouseById(item.id)">删除</button>
                </div>
            </div>
            <div class="field-list">
                <h1>田块列表</h1>
                <div v-for="(item) in fields" :key="item.id" class="field-item">🏠田块{{ item.id }}
                    <button @click="spaceAssembler.openEdit(item)">编辑</button>
                    <button @click="spaceAssembler.removeFieldById(item.id)">删除</button>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { onMounted, onBeforeUnmount, ref, Ref } from 'vue';
import * as THREE from 'three';
import * as TWEEN from '@tweenjs/tween.js';
import Light from '@/utils/Editor/Light';
import { enableAxesHelper } from '@/utils/Editor/Helper';
import CSSManager from '@/utils/Editor/Manager/CSSManager';
// 新封装的编辑器组件
import { getFieldDatas, getGreenHouseStructureDatas } from '@/editor/tools/mock';
import SpaceAssembler from '@/editor/SpaceAssembler';
import Controls from '@/editor/Controls';

let scene, renderer;


/**
 * @type{THREE.PerspectiveCamera}
 */
let camera: THREE.PerspectiveCamera;

let cssManager: CSSManager

let controls: Controls;

function animate() {
    requestAnimationFrame(animate);
    TWEEN.update();
    renderer.render(scene, camera);
    cssManager && cssManager.render()
    controls && controls.update();
    spaceAssembler && spaceAssembler.update()
}


let spaceAssembler: SpaceAssembler;

const greenhouses: Ref<Array<Editor.GreenHouse>> = ref([])

function loadSpaceAssembler() {

    /** 模拟加载已有温室 */
    const preloadGreenHouseDatas = getGreenHouseStructureDatas()
    const preloadFieldDatas = getFieldDatas()
    spaceAssembler = new SpaceAssembler({
        controls,
        camera,
        scene,
        renderer,
        preloadGreenHouses: preloadGreenHouseDatas,
        preloadFields: preloadFieldDatas,
    })
    spaceAssembler.on(SpaceAssembler.EVENT_BUILDING_UPDATE, ({ greenhouses: _greenhouses, fields: _fields }) => {
        _greenhouses && (greenhouses.value = _greenhouses)
        _fields && (fields.value = _fields)
    })
}

function handleAddGreenHouse() {
    spaceAssembler && spaceAssembler.addGreenHouse({
        id: Date.now(),
        enableWetCurtain: true,
        proofType: 'round',
        pos: {
            position: { x: 500 * greenhouses.value.length, y: 0, z: 0 },
        },
        scale: {
            x: 1,
            y: 1.5,
            z: 4,
        },
    })
}

const fields: Ref<Array<Editor.Field>> = ref([])
function handleAddField() {
    spaceAssembler && spaceAssembler.addField({
        id: Date.now(),
        scale: {
            base: 1.5,
            x: 1,
            y: 1,
            z: 1,
        },
        url: '3D/field/field1.fbx',
    })
}

/**
 * @type {Light}
 */
let light;

// 重构init函数，接收初始模式参数
function init() {
    const box = document.getElementById('THREE-canvas');
    scene = new THREE.Scene();
    camera = new THREE.PerspectiveCamera(75, box.clientWidth / box.clientHeight, 0.1, 5000);
    camera.position.set(1500, 1500, 1000);
    // camera.position.set(100, 100, 100);
    renderer = new THREE.WebGLRenderer({ antialias: true, canvas: box });
    renderer.setSize(box.clientWidth, box.clientHeight);
    renderer.setPixelRatio(window.devicePixelRatio);
    renderer.setClearColor(0x000000);

    enableAxesHelper(scene)

    light = new Light({ scene })
    // 添加网格辅助线
    const grid = new THREE.GridHelper(2000, 50, 0xffffff, 0xffffff);
    grid.material.opacity = 0.2;
    grid.material.transparent = true;
    scene.add(grid);


    // 创建控制器
    controls = new Controls({
        camera,
        scene,
        renderer,
        boxId: 'editor-box'
    })

    // 创建CSS管理器
    cssManager = new CSSManager({ camera, scene, renderer, containerId: 'editor-box' })

    loadSpaceAssembler()

    animate();

}

onMounted(() => {
    init();
});

onBeforeUnmount(() => {
    if (renderer) renderer.dispose();
    TWEEN.removeAll();
    spaceAssembler && spaceAssembler.destroy();
});
</script>


<style lang="scss" scoped>
#container {
    width: 100%;
    height: 100%;
    display: flex;
    $panelWidth: 20%;

    #editor-box {
        width: calc(100% - #{$panelWidth});
        height: 100%;
        position: relative;

        #THREE-canvas {
            width: 100%;
            height: 100%;
            position: absolute;
            top: 0;
            left: 0;
            z-index: 1;
        }
    }

    .panel {
        display: flex;
        flex-direction: column;
        width: $panelWidth;
        height: 100%;
        background-color: #fff;

        input,
        button {
            width: 60%;
            margin-bottom: 5px;
        }

        .greenhouse-list {
            display: flex;
            flex-direction: column;
            width: 100%;

            .greenhouse-item {
                width: 100%;

                button {
                    width: 50px;
                    margin-right: 5px;
                }
            }
        }

        .field-list {
            display: flex;
            flex-direction: column;
            width: 100%;

            .field-item {
                width: 100%;

                button {
                    width: 50px;
                    margin-right: 5px;
                }
            }
        }
    }
}
</style>